<template>
    <div class="Alphabet">
        <ul class="list">
            <li class="item" 
                v-for="(item, index) of letters" 
                :key="index"
                @touchstart="handleTouchStart"
                @touchmove="handleTouchMove"
                @touchend="handleTouchEnd"
                @click="handleClick"
                :ref="item"
            >{{item}}</li>
        </ul>
    </div>
</template>
<script>
export default {
    name:"CityAlphabet",
    props: {
        cities: Object
    },
    data () {
        return {
            touchStatus: false,
            startY: 0,
            timer: null
        }
    },
    computed: {
        letters () {
            const letters = []
            // 应该是作用域的问题，加了下面的判断条件之后，letters就成为了空数组，
            // 但还是不太理解原因???
            // if (!this.cities) {
                for (let i in this.cities) {
                    letters.push(i);
                }
            // }
            return letters
        }
    },
    // 8-7性能优化-1
    // 当从City.Vue传入Alphabet的city的值发生变化的时候，alphabet会重新渲染
    // 此时updated生命周期钩子函数会被执行
    updated () {
        this.startY = this.$refs['A'][0].offsetTop
    },
    methods: {
        handleClick (e) {
            this.$emit('change', e.target.innerText)
            // console.log(e.target.innerText)
        },
        handleTouchStart () {
            this.touchStatus = true
        },
        // 8-7性能优化-2
        handleTouchMove (e) {
            if (this.touchStatus) {
                // 计算A的高度，再计算手指滑动过的元素的高度，差值即可获得元素索引
                // console.log(this.$refs['A'][0].offsetTop)
                // console.log(e.touches[0].clientY)
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout( () => {
                    const moveY = e.touches[0].clientY-79
                    const index = Math.floor((moveY-this.startY)/20)
                    if (index >= 0 && index < this.letters.length) {
                        this.$emit('change', this.letters[index])
                    }
                }, 8)
                    
            }
        },
        handleTouchEnd () {
            this.touchStatus = false
        }
    }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
    .list
        position: absolute 
        top: 1.58rem
        right: 0
        bottom: 0
        width: .4rem
        display: flex
        flex-direction: column
        justify-content: center
        .item
            line-height: .4rem
            text-align: center
            color: $bgColor
            
        
</style>